package com.shou.auth.service;

import com.shou.auth.model.User;
import com.shou.auth.repository.UserRepository;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Optional;
import java.util.UUID;

@Service
public class UserService implements UserDetailsService {
    private final UserRepository userRepository;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    // 1. 查找用户（修正方法名）
    public Optional<User> findByLoginName(String loginName) {
        return userRepository.findByLoginName(loginName);
    }

    // 2. 用户注册（修正字段）
    public User registerUser(String loginName, String password) {
        User user = new User();
        user.setUserId(UUID.randomUUID().toString());  // 生成唯一ID
        user.setLoginName(loginName);
        user.setPassword(passwordEncoder.encode(password));
        user.setName("默认名称");  // 必填字段，实际可从前端传入
        user.setUserCode("默认编码");
        user.setSex("未知");
        user.setDept("未分配");
        user.setIdCard("000000000000000000");
        user.setHomeAddress("未填写");
        user.setPostCode("000000");
        user.setEmail("default@example.com");
        user.setMobilePhone("00000000000");

        return userRepository.save(user);
    }

    // 3. 密码校验
    public boolean checkPassword(String rawPassword, String encodedPassword) {
        return passwordEncoder.matches(rawPassword, encodedPassword);
    }

    // 4. Spring Security 用户认证
    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        User user = userRepository.findByLoginName(loginName)
                .orElseThrow(() -> new UsernameNotFoundException("用户未找到：" + loginName));
        
        return org.springframework.security.core.userdetails.User
                .withUsername(user.getLoginName())
                .password(user.getPassword())
                .roles("USER")
                .build();
    }
}
